import api from '../../../services/api'
import {defineStore} from "pinia";
import {Pagination, Record, Filters, Sorting,} from "../types";

const draw = async (filters: Filters) => {
  try {
    const res = await api.post('/admin/lottery/activity/draw', filters)
    return res.data.data;
  } catch (err) {
    console.error(err);
  }
  return null;
};

const drawUserList = async (options: Partial<Sorting> & Pagination & Filters) => {
  try {
    const res = await api.post('/admin/lottery/user/draw/page', {
      "activityId": options?.activityId,
      "pageNumber": options?.pageNumber,
      "pageSize": options?.pageSize,
    })
    return {
      data: res.data.data.content,
      pagination: {
        page: res.data.data.pageable.pageNumber,
        perPage: options.perPage,
        total: res.data.data.totalElements,
      },
    }
  } catch (err) {
    console.error(err);
  }
  return {
    data: [],
    pagination: {
      page: 0,
      perPage: 0,
      total: 0,
    },
  };
};

export const useDrawStore = defineStore('draw', {
  state: () => {
    return {
      items: [] as Record[],
      pagination: {
        page: 1,
        perPage: 10,
        total: 0,
      } as Pagination,
    }
  },

  actions: {
    draw: async (options: {filters?: Partial<Filters> }) => {
      const res = await draw(
        {
          activityId: options.filters?.activityId,
          prizeId: options.filters?.prizeId,
          drawNumber: options.filters?.drawNumber
        });
      console.log(res)
      return res;
    },
    async drawUserList(options: {sorting?: Sorting; pagination: Pagination; filters?: Partial<Filters> }){
      const { data, pagination } = await drawUserList({
        ...options.filters,
        ...options.sorting,
        ...options.pagination,
      })
      this.items = data
      this.pagination = pagination
    },
  }
});
